/*
 * Copyright Aduna (http://www.aduna-software.com/) (c) 1997-2009.
 *
 * Licensed under the Aduna BSD-style license.
 */

package edu.tju.commons.collections.iterators;

import java.util.Iterator;

/**
 * A CloseableIterator that converts an iterator over objects of type <tt>S</tt>
 * (the source type) to an iterator over objects of type <tt>T</tt> (the target
 * type).
 */
public abstract class ConvertingIterator<S, T> extends CloseableIteratorBase<T> {

	/**
	 * The source type iterator.
	 */
	private final Iterator<? extends S> iter;

	/**
	 * Creates a new ConvertingIterator that operates on the supplied source type
	 * itertor.
	 * 
	 * @param iter
	 *        The source type itertor for this <tt>ConvertingIterator</tt>, must
	 *        not be <tt>null</tt>.
	 */
	public ConvertingIterator(Iterator<? extends S> iter) {
		assert iter != null;
		this.iter = iter;
	}

	/**
	 * Converts a source type object to a target type object.
	 */
	protected abstract T convert(S sourceObject);

	/**
	 * Checks whether the source type itertor contains more elements.
	 * 
	 * @return <tt>true</tt> if the source type itertor contains more elements,
	 *         <tt>false</tt> otherwise.
	 */
	public boolean hasNext() {
		return iter.hasNext();
	}

	/**
	 * Returns the next element from the source type itertor.
	 * 
	 * @throws java.util.NoSuchElementException
	 *         If all elements have been returned.
	 * @throws IllegalStateException
	 *         If the itertor has been closed.
	 */
	public T next() {
		return convert(iter.next());
	}

	/**
	 * Calls <tt>remove()</tt> on the underlying itertor.
	 * 
	 * @throws UnsupportedOperationException
	 *         If the wrapped itertor does not support the <tt>remove</tt>
	 *         operation.
	 * @throws IllegalStateException
	 *         If the itertor has been closed, or if {@link #next} has not yet
	 *         been called, or {@link #remove} has already been called after the
	 *         last call to {@link #next}.
	 */
	public void remove() {
		iter.remove();
	}

	/**
	 * Closes this itertor as well as the wrapped itertor if it is a
	 * {@link CloseableIterator}.
	 */
	@Override
	protected void handleClose() {
		super.handleClose();
		Iterators.closeCloseable(iter);
	}
}
